/*****************************************************************************
 *  TouchMe
 *  Copyright (C) 2010  Daniel Lerch Hostalot <dlerch@gmail.com>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *****************************************************************************/


#include<stdio.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>

#include "util.h"
#include "common.h"


point_t calib[9];

int main(int argc, char **argv)
{
	struct input_event ev;
	int x=0;
	int y=0;
	int xmax=0;
	int ymax=0;
	int xi=0;
	int yi=0;
	int i=0;

	Display *display = XOpenDisplay(getenv("DISPLAY"));

	get_screen_size(display, &xmax, &ymax);
	printf("screen size: %dx%d\n", xmax, ymax);


	if(argc!=2)
	{
		printf("Usage: %s [event file: /dev/input/event5]\n\n", argv[0]);
		return 0;
	}

	int fd=open(argv[1], O_RDONLY);
	if(fd<0)
	{
		perror("open()");
		return 0;
	}



	xi = xmax/4;
	yi = ymax/4;
	
	for(x=xi; x<=xmax-xi; x+=xi)	
	{
		for(y=yi; y<=ymax-yi; y+=yi)	
		{
			mouse_move(display, x, y);
			printf("Testing (%d, %d) position, please touch the mouse pointer\n",
				x, y);

			int evx=-1;
			int evy=-1;
			int end=0;
			while(!end) 
			{
				int r=read(fd, &ev, sizeof(struct input_event));
				if(r<0) continue;

				if(ev.type==3 && ev.code==4)
					evx = ev.value;

				else if(ev.type==3 && ev.code==5)
					evy = ev.value;

				else if(ev.type==1 && ev.code==272)
					if(ev.value==0)
						end=1;
			}

			calib[i].x = evx;
			calib[i].y = evy;
			i++;
			printf("Touch: (%d, %d)\n", evx, evy);
		}
	}

	FILE *f = fopen(CONFFILE, "w+");
	if(!f)
	{
		perror("fopen()");
		return 0;
	}

	for(i=0; i<9; i++)
		fprintf(f, "(%d, %d)\n", calib[i].x, calib[i].y);

	fclose(f);

	XCloseDisplay(display);
	return 0;
}






